<?php
/**
 * Created by PhpStorm.
 * User: Guan
 * Date: 2018/3/27
 * Time: 13:51
 */

namespace app\admin\logic;

use \app\admin\model\Banji as Banjimodel;
use think\Cache;
use function PHPSTORM_META\type;
use nx\Data;

class Banji
{
    public $Banji_model = '';

    public function getModel()
    {
        if (empty($this->Banji_model)) {
            $this->Banji_model = new Banjimodel();
        }
        return $this->Banji_model;
    }

    public function getbanjiall()
    {
        $Banjis = Cache::get('allBanjis');
        if (!empty($Banjis)) {
            return $Banjis;
        }
        $Banjis = $this->getModel()->where('status',1)->order('sort')->select();
        if (empty($Banjis)) {
            return $Banjis;
        }
        $Banjis = collection($Banjis)->append()->toArray();
        foreach ($Banjis as $k=>$v){
            if ($v['status']==1){
                $Banjis[$k]['status_text'] ='正常';
            }
        }
        Cache::set('allOBanjis', $Banjis);
        return $Banjis;
    }

    public function addBanji($data)
    {
        if (empty($data)) {
            return ['result' => false, 'msg' => '数据丢失'];
        }
        if (!empty($data['code'])) {
            $data['code'] = strtoupper(trim($data['code']));
        }
        $result = $this->getModel()->allowField(true)->save($data);
        if (false === $result) {
            return ['result' => false, 'msg' => $this->getModel()->getError()];
        } else {
            Cache::rm('allOBanjis');
            return ['result' => true, 'msg' => '班级添加成功'];
        }
    }



    public function editBanji($data)
    {
        if (empty($data['id'])) {
            return ['result' => false, 'msg' => 'ID丢失'];
        }
        isset($data['status']) ?: $data['status'] = 0;
        $result = $this->getModel()->allowField(true)->isUpdate(true)->save($data);
        if (false === $result) {
            return ['result' => false, 'msg' => $this->getModel()->getError()];
        } else {
            Cache::rm('allOrigins');
            return ['result' => true, 'msg' => '班级修改成功'];
        }
    }

    public function delBanji($id)
    {
        if (empty($id)) {
            return ['result' => false, 'msg' => '请选择要操作的数据'];
        }
        if (Banjimodel::get($id)) {
            if (Banjimodel::destroy($id)) {
                Cache::rm('allBanji');
                return ['result' => true, 'msg' => '删除成功'];
            } else {
                return ['result' => false, 'msg' => '删除失败'];
            }
        } else {
            return ['result' => false, 'msg' => '要删除的数据不存在'];
        }
    }
}